#!/bin/bash

lib_path="./lib"
framework_prefix="ablecloud-framework"
framework=""

conf_file=""
mode="test"
user_lib_path=""
uds_id=""
mx="1024"
ms="256"

usage() {
    echo "Usage: $0 [-c conf_file] [-l user_lib_path] [-m mode] [-i identity] [-x maximum_memory_in_MB] [-s minimum_memory_in_MB]"
    echo "    -c: specify user-defined configuration file."
    echo "    -l: specify library path which you will used excluding framework and framework's lib."
    echo "    -m: specify run mode. should be one of [test,production], default is production."
    echo "    -i: identity of the UDS: domainId_subDomainId_serviceName_serviceVersion."
    echo "    -x: maximum memory in MB which can be used by the JVM."
    echo "    -s: minimum memory in MB which should be allocated for the JVM."
}

while getopts "c:l:m:i:x:s:h" opt
do
    case ${opt} in
        c)
            conf_file=$OPTARG
            ;;
        l)
            user_lib_path=$OPTARG
            ;;
        m)
            mode=$OPTARG
            if [ "${mode}" != "test" ] && [ "${mode}" != "production" ]
            then
                usage
                exit 1
            fi
            ;;
        i)
            uds_id=$OPTARG
            ;;
        x)
            mx=$OPTARG
            ;;
        s)
            ms=$OPTARG
            ;;
        h)
            usage
            exit 1
            ;;
        ?)
            usage
            exit 1
            ;;
    esac
done

framework=`ls ${lib_path}/${framework_prefix}*.jar`
fw_num=`echo ${framework} | awk -F' ' '{print NF}'`
if [ ${fw_num} -lt 1 ]
then
    echo "could not find cloud service framework jar file"
    exit 2
elif [ ${fw_num} -gt 1 ]
then
    echo "find more than one cloud service framework jar files["${framework}"]"
    exit 2
else
    framework=`echo ${framework} | awk -F' ' '{print $1}'`
fi

param="-Xbootclasspath/a:"
libs=`ls ${lib_path}/*.jar`
for lib in ${libs}
do
    param=${param}${lib}:
done

if [ -n "${user_lib_path}" ] && [ "${user_lib_path}" != "${lib_path}" ]
then
    libs=`ls ${user_lib_path}/*.jar`
    for lib in ${libs}
    do
        param=${param}${user_lib_path}"/"${lib}:
    done
fi

args="-Dmode=${mode} "
if [ -n "$conf_file" ]
then
    args=${args}"-Dconf_file=${conf_file}"
fi
if [ -n "$uds_id" ]
then
    args=${args}"-Duds_id=${uds_id}"
fi

exec java ${param} ${args} -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -Xmx${mx}m -Xms${ms}m -jar ${framework}